# 导入库
from py_commander import Network
import time
import threading

target_ip = "192.168.189.1"
command = """
cd D:\\test
python cmd_test.py
"""

def process_received_message(msg):
    """处理接收到的消息"""
    if not msg:
        return False
        
    message_content = msg.get('message', '')
    sender = msg.get('sender', 'unknown')
    print("收到来自 {0} 的消息: {1}".format(sender, message_content))
    
    # 根据消息内容执行不同操作，但不特殊处理控制消息
    if message_content == "开始":
        print("收到消息：开始")
        # 这里可以添加特定的业务逻辑处理
    elif message_content == "暂停":
        print("收到消息：暂停")
        # 这里可以添加特定的业务逻辑处理
    elif message_content == "停止":
        print("收到消息：停止")
        return True  # 返回True表示应该退出程序
    else:
        print("处理消息: {0}".format(message_content))
        # 这里可以添加其他消息的处理逻辑
        
    return False  # 继续程序执行

def show_menu():
    """显示控制菜单"""
    print("\n--- 控制菜单 ---")
    print("1. 开始监听消息")
    print("2. 暂停监听消息")
    print("3. 发送测试消息")
    print("4. 发送测试文件")
    print("5. 发送测试命令")
    print("0. 退出程序")
    choice = input("请输入选项: ")
    return choice

# 启动服务器
server_thread = Network.start_server(port=9999)
print("服务器已启动，等待消息...")

# 创建测试文件
with open('test.txt', 'w') as file:
    file.write('Hello, World!\n')

# 程序主循环
should_exit = False
while not should_exit:
    # 显示菜单
    choice = show_menu()
    
    if choice == '1':
        Network.resume_listening()
        print("已开始监听消息")
    elif choice == '2':
        Network.pause_listening()
        print("已暂停监听消息")
    elif choice == '3':
        print("发送测试消息...")
        response = Network.send_message(target_ip, "测试消息", port=9999)
        print("消息发送结果:", response)
    elif choice == '4':
        print("发送测试文件...")
        remote_path = r"D:\test\test.txt"
        response = Network.send_file(target_ip, 'test.txt', remote_path, port=9999)
        print("文件传输结果:", response)
    elif choice == '5':
        print("发送测试命令...")
        response = Network.send_command(target_ip, command, port=9999, timeout=60)
        print("命令执行结果:", response)
    elif choice == '0':
        should_exit = True
    else:
        print("无效的选项，请重新输入")
    
    # 处理接收到的消息
    msg = Network.get_message()
    if msg:
        should_exit = process_received_message(msg)
    
    # 避免CPU占用过高
    time.sleep(0.1)

# 程序结束时关闭服务器
print("程序结束，关闭服务器...")
Network.stop_server()
print("服务器已关闭")




#### 添加关闭server的方法











